/*-
 * Copyright (c) 2005 - 2014 CAS Dev Team
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the CAS Dev. Team nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *      HTTPRedirectView.hpp
 *
 * $CAS$
 */

#include "CTPPView.hpp"
using namespace CAS;

namespace TEST_NS {

class HTTPRedirectView: public CTPPView {
public:
	/**
	 @brief A virtual destructor
	 */
	~HTTPRedirectView() throw ();

	/**
	 @brief Constructor
	 */
	HTTPRedirectView();
private:
	/**
	 @brief Prepare response/parameters before processing template. Parameters are the same as in WriteResponse()
	 */
	virtual INT_32 WriteResponse(CTPP::CDT & data, ASResponse & response,
			ASResponseWriter & responseWriter, ASPool & globalPool,
			ASPool & vhostPool, ASPool & requestPool, CTPP::CDT & configuration,
			ASObject * contextData, CTPP::CDT & imc, ASLogger & logger);
	/**
	 @brief Get handler name
	 */
	CCHAR_P GetObjectName() const;
};

EXPORT_HANDLER(HTTPRedirectView)

// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Class HTTPRedirectView
//

//
// A constructor
//
HTTPRedirectView::HTTPRedirectView() {
	;;
}

//
// Get handler name
//
CCHAR_P HTTPRedirectView::GetObjectName() const {
	return "HTTPRedirectView";
}

INT_32 HTTPRedirectView::WriteResponse(CTPP::CDT & data, ASResponse & response,
		ASResponseWriter & responseWriter, ASPool & globalPool,
		ASPool & vhostPool, ASPool & requestPool, CTPP::CDT & configuration,
		ASObject *contextData, CTPP::CDT & imc, ASLogger & logger) {
	// Get content type
	const STLW::string contentType = response.GetContentType();
	const STLW::string url = imc.GetCDT("redirect.url").GetString();
	STLW::string templateName = imc["template"].GetString();

	bool useHTMLRedirect = false;
	bool isWml = contentType.find("wml") != STLW::string::npos;
	// For non-WML clients if client is MSIE and via going to HTTPS url from HTTP referer then redirect via HTML-tag
	// TODO check whether request accepts HTML ?
	if (!isWml) {
		bool fieldExists;
		const CTPP::CDT& headers = imc.GetExistedCDT("redirect.headers",
				fieldExists);
		if (fieldExists) {
			STLW::string userAgent = headers["User-Agent"].GetString();
			// Check MSIE
			if (userAgent.find("MSIE") != STLW::string::npos) {
				const STLW::string referer = headers["Referer"].GetString();
				bool refererIsHttps = referer.find("https://") == 0;
				bool urlIsHttps = url.find("https://") == 0;
				// Schemes differs?
				if (refererIsHttps != urlIsHttps) {
					useHTMLRedirect = true;
				}
			}
		}
	}

	if (!useHTMLRedirect) {
		response.Redirect(url);
		responseWriter.WriteHeader(response);
		logger.Debug("Sent redirect");
	} else {
		response.SetContentType(isWml ? "text/vnd.wap.wml" : "text/html");
		logger.Debug("Using HTML redirect");
		// TODO do we really need WML stuff ?
		if (templateName.empty()) {
			imc["template"] =
					isWml ? "redirect/wml-redirect.tmpl" : "redirect/html-redirect.tmpl";
		}
		data["redirect.url"] = url;
		response.OK();
		return CTPPView::WriteResponse(data, response, responseWriter,
				globalPool, vhostPool, requestPool, configuration, contextData,
				imc, logger);
	}
	return VIEW_OK;

}

//
// A destructor
//
HTTPRedirectView::~HTTPRedirectView() throw () {
}

} // namespace TEST_NS
// End.
